package com.xmh.reptile.service;

import cn.hutool.core.io.FileUtil;
import com.xmh.reptile.util.RedisMockUtil;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class NovelAhfgbService {

    public static int errorCount = 0;

    public static final String key = "万古至尊";

    public static long newPageNumber = Long.parseLong(String.valueOf(RedisMockUtil.get(key) == null ? 0 : RedisMockUtil.get(key)));

    public static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");

    public static void wgzz() throws InterruptedException {
        StringBuilder sb = new StringBuilder();
        try {
            Document doc = Jsoup.connect("https://www.ahfgb.com/27_27143/").get();

            Elements list = doc.getElementById("list").select("dd a");

            for (Element element : list) {
                String href = element.attr("href");

                String title = element.html();

                String number = extractNumbersFromString(title);

                if (Integer.parseInt(number) < 198) {
                    continue;
                }

                System.out.println(title);

                String pageNumber = StringUtils.substringAfterLast(href, "/").split("\\.")[0];

                if (Long.parseLong(pageNumber) <= newPageNumber) {
                    continue;
                } else {
                    newPageNumber = Long.parseLong(pageNumber);
                }

                sb.append("\n\n====== ").append(title).append(" =====\n\n");
//                https://www.ahfgb.com/27_27143/115902.html
                Element select = callAgain("https://www.ahfgb.com" + href).getElementById("content");

                String text = textHandle(select.html());

                sb.append(text);

                Thread.sleep(1000);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (StringUtils.isNotEmpty(sb.toString())) {
            FileUtil.appendString(sb.toString(), new File("C:\\Users\\12425\\OneDrive\\桌面\\test" + simpleDateFormat.format(new Date()) + ".txt"), "UTF-8");
            RedisMockUtil.set(key, newPageNumber);
        }
    }

    public static String extractNumbersFromString(String str) {
        StringBuilder builder = new StringBuilder();

        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if (Character.isDigit(ch)) {
                builder.append(ch);
            }
        }

        return builder.toString();
    }

    private static Document callAgain(String url) throws InterruptedException {
        try {
            Document doc = Jsoup.connect(url).get();
            errorCount = 0;
            System.out.println("success get url !!!");
            return doc;
        } catch (Exception e) {
            System.out.println("have a error, errorCount: " + (errorCount + 1));
            if (errorCount++ > 10) {
                throw new RuntimeException();
            }
            Thread.sleep(5000);
            return callAgain(url);
        }
    }

    private static String textHandle(String text) {
        String result = text.replace("<br>", "");
        result = result.replace("由于各种问题biquge.biz地址更改为ahfgb.com请大家收藏新地址避免迷路", "");
        result = result.replace("网页版章节内容慢，请下载好阅小说app阅读最新内容", "");
        result = result.replace("请退出转码页面，请下载好阅小说app 阅读最新章节。", "");
        result = result.replace(" 笔趣鸽为你提供最快的洛青舟秦蒹葭全文阅读完整版更新，第1章 好消息免费阅读。https://www.ahfgb.com", "");
        result = result.replace("\n\n\n", "\n\n");
        result = result.replace("\n\n\n\n\n", "\n\n");
        result = result.replace("\n\n\n\n\n\n\n", "\n\n");
        result = result.replace(" \n\n\n\n\n\n\n\n", "\n\n");
        return result;
    }

}
